package net.boot.smpp.utils;

import lombok.extern.slf4j.Slf4j;
import org.jsmpp.InvalidResponseException;
import org.jsmpp.PDUException;
import org.jsmpp.bean.*;
import org.jsmpp.extra.NegativeResponseException;
import org.jsmpp.extra.ProcessRequestException;
import org.jsmpp.extra.ResponseTimeoutException;
import org.jsmpp.session.*;
import org.jsmpp.util.AbsoluteTimeFormatter;
import org.jsmpp.util.InvalidDeliveryReceiptException;
import org.jsmpp.util.TimeFormatter;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * @author qiusu
 * @since 2025/8/18 16:24
 */
@Slf4j
public class SimpleSubmitSmppUtil {


    private static final TimeFormatter TIME_FORMATTER = new AbsoluteTimeFormatter();

    public static void sendSimpleMessage(Map<String, Object> params) {

        String server = params.getOrDefault("server", "localhost").toString();
        int port = (int) params.get("port");
        String message = params.getOrDefault("message", "hello world").toString();
        String systemId = params.getOrDefault("systemId", "tb").toString();
        String password = params.getOrDefault("password", "xrf12345").toString();
        String systemType = params.getOrDefault("systemType", "cp").toString();
        String serviceType = params.getOrDefault("serviceType", "CMT").toString();
        String sourceAddr = params.getOrDefault("sourceAddr", "10123456789").toString();
        String destinationAddr = params.getOrDefault("destinationAddr", "10123456789").toString();

        SMPPSession session = new SMPPSession();
        // Set listener to receive deliver_sm
        session.setMessageReceiverListener(new MessageReceiverListener() {

            public void onAcceptDeliverSm(DeliverSm deliverSm) throws ProcessRequestException {
                if (MessageType.SMSC_DEL_RECEIPT.containedIn(deliverSm.getEsmClass())) {
                    // delivery receipt
                    try {
                        DeliveryReceipt delReceipt = deliverSm.getShortMessageAsDeliveryReceipt();
                        long id = Long.parseLong(delReceipt.getId()) & 0xffffffff;
                        String messageId = Long.toString(id, 16).toUpperCase();
                        log.info("received '{}' : {}", messageId, delReceipt);
                    } catch (InvalidDeliveryReceiptException e) {
                        log.error("receive failed, e");
                    }
                } else {
                    // regular short message
                    log.info("Receiving message : {}", new String(deliverSm.getShortMessage()));
                }
            }

            public void onAcceptAlertNotification(AlertNotification alertNotification) {
                log.info("Receiving alert for {} from {}", alertNotification.getSourceAddr(), alertNotification.getEsmeAddr());
            }

            public DataSmResult onAcceptDataSm(DataSm dataSm, Session source) throws ProcessRequestException {
                log.info("onAcceptDataSm");
                return null;
            }
        });

        try {

            String SMS_systemId = session.connectAndBind(server, port, new BindParameter(BindType.BIND_TRX, systemId, password, systemType,
                    TypeOfNumber.UNKNOWN, NumberingPlanIndicator.UNKNOWN, null));
            log.info("Connected with SMSC with system id {}", SMS_systemId);

            // send Message
            try {
                // set RegisteredDelivery
                final RegisteredDelivery registeredDelivery = new RegisteredDelivery();
                registeredDelivery.setSMSCDeliveryReceipt(SMSCDeliveryReceipt.SUCCESS_FAILURE);

                SubmitSmResult submitSmResult = session.submitShortMessage(serviceType, TypeOfNumber.INTERNATIONAL,
                        NumberingPlanIndicator.UNKNOWN, sourceAddr, TypeOfNumber.INTERNATIONAL, NumberingPlanIndicator.UNKNOWN,
                        destinationAddr, new ESMClass(), (byte)0, (byte)1, TIME_FORMATTER.format(new Date()), null,
                        registeredDelivery, (byte)0, new GeneralDataCoding(Alphabet.ALPHA_DEFAULT, MessageClass.CLASS1,
                                false), (byte)0, message.getBytes());

                String messageId = submitSmResult.getMessageId();
                log.info("Message submitted, message_id is {}", messageId);

            } catch (PDUException e) {
                // Invalid PDU parameter
                log.error("Invalid PDU parameter", e);
            } catch (ResponseTimeoutException e) {
                // Response timeout
                log.error("Response timeout", e);
            } catch (InvalidResponseException e) {
                // Invalid response
                log.error("Receive invalid response", e);
            } catch (NegativeResponseException e) {
                // Receiving negative response (non-zero command_status)
                log.error("Receive negative response", e);
            } catch (IOException e) {
                log.error("I/O error occurred", e);
            }

            // wait 3 second
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                log.info("Interrupted exception", e);
            }

            // unbind(disconnect)
            session.unbindAndClose();

        } catch (IOException e) {
            log.error("Failed connect and bind to host", e);
        }
        log.info("Finish!");
    }
}
